class Solution { 
public:
    int scheduleCourse(vector<vector<int>>& courses) {
        sort(courses.begin(), courses.end(), [](const auto& e1, const auto& e2){
            return e1[1] < e2[1];
        });
        priority_queue<int> heap;
        int time = 0;
        for(const auto& e : courses)
        {
            if(time + e[0] <= e[1])
            {
                time += e[0];
                heap.push(e[0]);
            }
            else
            {
                if(!heap.empty() && heap.top() > e[0])
                {
                    time += e[0] - heap.top();
                    heap.pop();
                    heap.push(e[0]);
                }
            }
        }
        return heap.size();
    }
};
